package com.darren.euc.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.entity.Manager;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.Role;
import com.darren.euc.entity.User;
import com.darren.euc.service.ManagerService;
import com.darren.euc.service.RoleService;
import com.darren.euc.service.UserService;
import com.darren.euc.util.PropertyHelper;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/manager")
public class ManagerAction {
	
	private static final Logger log = Logger.getLogger(ManagerAction.class);
	
	@Autowired
    private ManagerService managerService;	
	
	@Autowired
    private UserService userService;
	
	@Autowired
    private RoleService roleService;
		
	@ResponseBody
    @RequestMapping(value = "/list")
    public PageBean getManagerList(HttpServletRequest request,HttpServletResponse response) {
        return managerService.queryForPageUseHQLByRoleId(null, PropertyHelper.getPageSize(), 1);
    }

	@ResponseBody
    @RequestMapping(value = "/manager")//,method = RequestMethod.POST)
    public Manager getManager(HttpServletRequest request,HttpServletResponse response) {
    	List<Manager> managers = managerService.getAll();
    	Manager manager = managers.get(0);
        return manager;
    }	
	
	@ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public ResponseJSON queryManager(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		PageBean pageBean = managerService.queryForPageUseSQLByRoleName(requestJson.getJSONObject("data"), PropertyHelper.getPageSize(), requestJson.getInt("currentPage"));
		responseJson.setData(pageBean);
		return responseJson;
    }
	
	
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResponseJSON addManager(@RequestBody JSONObject requestJson, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			String roleName = requestJson.getString("roleName");
			String mobile = requestJson.getString("mobile");
			List<User> users = userService.getUserByMobile(mobile);
			if(users == null || users.size() <= 0){
				responseJson.setStatus(-1);
				responseJson.setMessage("你输入的手机号在系统中不存在，请核对后再输！");
			}else{
				List<Role> roles = roleService.getRoleByRoleName(roleName);
				List<Manager> managers = new ArrayList<Manager>();
				for(int i = 0; i < roles.size(); i++){
					Role role = roles.get(i);
					for(int j = 0; j < users.size(); j++){
						User user = users.get(j);
						Manager manager = managerService.getManagerByRoleIdAndUserId(role.getId().toString(), user.getId().toString());
						if(manager == null){
							manager = new Manager();
							manager.setUser(user);
							manager.setRole(role);
							manager.setCreateTime(new Date());
							manager = managerService.save(manager);
						}
						managers.add(manager);
					}
				}
				if(managers.size() > 0){
					responseJson.setStatus(0);
					responseJson.setMessage("添加成功！");
				}else{
					responseJson.setStatus(-2);
					responseJson.setMessage("添加失败！");
				}
				responseJson.setData(managers);
			}
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-3);
			responseJson.setMessage("添加失败！");
		}
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
    
    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public ResponseJSON deleteManager(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	responseJson.setData(jsonData);
    	try{
    		Integer id = Integer.parseInt(requestJson.getString("id"));
    		managerService.deleteById(id);
        	responseJson.setStatus(0);
    		responseJson.setMessage("删除成功！");
    	}catch(Exception ex){
    		log.info(ex.getMessage(),ex);
        	responseJson.setStatus(-1);
    		responseJson.setMessage("删除失败！");
    	}
    	System.out.println("==============================================================");
    	System.out.println(requestJson.toString());
    	System.out.println(responseJson.toString());
    	System.out.println("==============================================================");
        return responseJson;
    } 
    
    
    @SuppressWarnings("unused")
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseJSON updateManager(@RequestBody JSONObject requestJson, HttpServletRequest request,
			HttpServletResponse response) {
    	//{managerId:manager.id,roleName:roleName,mobile:mobile}
		ResponseJSON responseJson = new ResponseJSON();
		try {
			String roleName = requestJson.getString("roleName");
			String mobile = requestJson.getString("mobile");
			String managerId = requestJson.getString("managerId");
			List<User> users = userService.getUserByMobile(mobile);
			if(users == null || users.size() <= 0){
				responseJson.setStatus(-1);
				responseJson.setMessage("你输入的手机号在系统中不存在，请核对后再输！");
			}else{
				Manager manager = managerService.findManagerById(Integer.parseInt(managerId));
				List<Role> roles = roleService.getRoleByRoleName(roleName);
				for(int j = 0; j < users.size(); j++){
					User user = users.get(j);
					Manager managerBySearch = managerService.getManagerByRoleIdAndUserId(manager.getRoleId(), user.getId().toString());
					if(managerBySearch != null){
						manager.setUser(user);
						if(roles != null && roles.size() > 0){
							manager.setRole(roles.get(0));
						}						
						managerService.update(manager);
					}
				}
				
				
//				List<Role> roles = roleService.getRoleByRoleName(roleName);
//				List<Manager> managers = new ArrayList<Manager>();
//				for(int i = 0; i < roles.size(); i++){
//					Role role = roles.get(i);
//					for(int j = 0; j < users.size(); j++){
//						User user = users.get(j);
//						Manager manager = managerService.getManagerByRoleIdAndUserId(role.getId().toString(), user.getId().toString());
//						if(manager == null){
//							manager = new Manager();
//							manager.setUser(user);
//							manager.setRole(role);
//							manager.setCreateTime(new Date());
//							manager = managerService.save(manager);
//						}
//						managers.add(manager);
//					}
//				}
				
//				
//				if(managers.size() > 0){
//					responseJson.setStatus(0);
//					responseJson.setMessage("修改成功！");
//				}else{
//					responseJson.setStatus(-2);
//					responseJson.setMessage("修改失败！");
//				}
//				
				responseJson.setStatus(0);
				responseJson.setMessage("修改成功！");
				responseJson.setData(manager);
			}
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-3);
			responseJson.setMessage("修改失败！");
		}
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
    
}